package com.haiyuancloud.server.auth.handler;

import com.haiyuancloud.auth.service.TbLogLoginService;
import com.haiyuancloud.common.core.entity.HaiyuanAuthUser;
import com.haiyuancloud.common.core.entity.HaiyuanResponse;
import com.haiyuancloud.common.core.utils.HaiyuanUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author haiyuan
 */
@Slf4j
@Component
public class HaiyuanWebLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private final RequestCache requestCache = new HttpSessionRequestCache();

    @Resource
    private TbLogLoginService tbLogLoginService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        log.info("@@@@@@onAuthenticationSuccess@@@@@@@@@@@");
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object attribute = session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
            log.info("跳转到登录页的地址为: {}", attribute);
        }
        if (HaiyuanUtil.isAjaxRequest(request)) {
            HaiyuanResponse data = new HaiyuanResponse();
            if (savedRequest == null) {
                HaiyuanUtil.makeFailureResponse(response, data.message("请通过授权码模式跳转到该页面"));
                return;
            }
            data.data(savedRequest.getRedirectUrl());
            insert(request,1,"登录成功");
            HaiyuanUtil.makeSuccessResponse(response, data);
        } else {
            if (savedRequest == null) {
                insert(request,1,"登录成功");
                super.onAuthenticationSuccess(request, response, authentication);
                return;
            }
            clearAuthenticationAttributes(request);
            getRedirectStrategy().sendRedirect(request, response, savedRequest.getRedirectUrl());
        }
    }

    private  void insert (HttpServletRequest request,Integer flag,String message){
        Integer src = Integer.parseInt(request.getParameter("src"));
        HaiyuanAuthUser currentUser = (HaiyuanAuthUser) request.getSession().getAttribute("authUser");
        tbLogLoginService.insert(  currentUser,  src,  flag,  message);
    }
}
